package com.zly.jwt.handler;

import com.alibaba.fastjson2.JSON;
import com.zly.jwt.entity.Result;
import com.zly.jwt.properties.JwtProperties;
import com.zly.jwt.utils.JwtUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

@Slf4j
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    private JwtProperties jwtProperties;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        JwtUtils jwtUtils = new JwtUtils();
        Date expirationDate = new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * jwtProperties.getExpiration());
        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("principal",authentication.getName());
        ArrayList<Object> arrayList = new ArrayList<>();
        for (GrantedAuthority authority : authentication.getAuthorities()) {
            arrayList.add(authority.getAuthority());
        }
        objectObjectHashMap.put("authority",arrayList);
        objectObjectHashMap.put("credential",authentication.getCredentials());
        String token = jwtUtils.generateToken("login", expirationDate, objectObjectHashMap, jwtProperties.getSecretKey());
        response.getWriter().write(JSON.toJSONString(Result.SUCCESS(200, "登陆成功", token)));
    }
}
